<template>
	<div class="tabs-box">
		<div class="tabs-menu">
			<el-tabs v-model="tabsMenuValue" type="card" @tab-click="tabClick" @tab-remove="tabRemove">
				<el-tab-pane
					v-for="(item, index) in tabsMenuList"
					:key="item.path"
					:label="item.title"
					:name="item.path"
					:closable="tabsMenuList.length != 1"
				>
					<template #label>
						<el-icon class="tabs-icon" v-if="item.icon && themeConfig.tabsIcon">
							<component :is="item.icon"></component>
						</el-icon>
						{{ item.title }}
					</template>
				</el-tab-pane>
			</el-tabs>
			<MoreButton />
		</div>
	</div>
</template>
<script lang="ts" setup>
import { GlobalStore } from "@/stores";
import { TabsStore } from "@/stores/modules/tabs";
import { TabsPaneContext } from "element-plus";
import Sortable from "sortablejs";
import { ref, computed, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { AuthStore } from "@/stores/modules/auth";
import MoreButton from "./components/MoreButton.vue";

const route = useRoute();
const router = useRouter();
const tabStore = TabsStore();
const globalStore = GlobalStore();
const authStore = AuthStore();

const tabsMenuValue = ref(route.fullPath);
const tabsMenuList = computed(() => tabStore.tabsMenuList);
const themeConfig = computed(() => globalStore.themeConfig);
const closeable = ref(true);

// 监听路由的变化，防止浏览器后退/前进不变化 tabsMenuValue）
watch(
	() => route.fullPath,
	() => {
		if (route.meta.isFull) return;
		tabsMenuValue.value = route.fullPath;
		const tabsParams = {
			icon: route.meta.icon as string,
			title: route.meta.title as string,
			path: route.fullPath,
			close: !route.meta.isAffix
		};
		tabStore.addTabs(tabsParams);
	},
	{
		immediate: true
	}
);

onMounted(() => {
	tabsDrop();
	initTabs();
});

// 标签拖拽排序
const tabsDrop = () => {
	Sortable.create(document.querySelector(".el-tabs__nav") as HTMLElement, {
		draggable: ".el-tabs__item",
		animation: 300,
		onEnd({ newIndex, oldIndex }) {
			// oldIndex拖放前的位置, newIndex拖放后的位置
			// const currentRow = tabsMenuList.value.splice(oldIndex as number, 1)[0];
			// tabsMenuList.value.splice(newIndex as number, 0, currentRow);
		}
	});
};

// 初始化需要固定的标签
const initTabs = () => {
	authStore.flatMenuListGet.forEach(item => {
		if (item.meta.isAffix && !item.meta.isHide && !item.meta.isFull) {
			const tabsParams = {
				icon: item.meta.icon,
				title: item.meta.title,
				path: item.path,
				close: !item.meta.isAffix
			};
			tabStore.addTabs(tabsParams);
		}
	});
};

const tabClick = (tabItem: TabsPaneContext) => {
	const fullPath = tabItem.props.name as string;
	router.push(fullPath);
};

const tabRemove = (fullPath: string) => {
	tabStore.removeTabs(fullPath, fullPath == route.fullPath);
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
